const storage = require('../../utils/storage')
const date = require('../../utils/date')

Page({
  data: {
    categories: [],
    categoriesState: [],
    // activeCategory: '', // 空字符串表示显示全部笔记
    notes: [],
    scrollTop: 0,
    newCategoryState: { category: '', visible: false },
    showSidebar: true,
    noteCounts: {},
    allNoteCounts: 0,
    config: { activeCategory: '' },
    actionState: { selectedCategory: '', checkedNotes: [], selectedAll: false },
    onAction: false
  },

  onLoad() {
    // wx.setStorageSync('notes_data', {})

    this.initConfig()
    this.initData()
  },

  onHide() {
    storage.setConfig(this.data.config)
  },

  onUnload() {
    storage.setConfig(this.data.config)
  },

  initConfig() {
    this.setData({ config: storage.getConfig() })
  },

  initData() {
    this.loadData()

    // 监听笔记更新事件
    const app = getApp()
    app.eventBus.on('noteUpdated', (note) => {
      this.loadData()
    })

    app.eventBus.on('noteDeleted', (noteId) => {
      this.loadData()
    })
  },

  loadData() {
    this.loadNotes(this.data.config.activeCategory)
    this.loadCategories()
    this.calculateCatNoteCounts()
  },

  loadCategories() {
    let categories = storage.getCategories()
    // 确保有"未分类"分类
    if (!categories.includes(storage.UNCATEGORIZED)) {
      categories.unshift(storage.UNCATEGORIZED)
    }

    const categoriesState = [...categories.map(c => ({
      category: c, isOriginCategory: c === storage.UNCATEGORIZED
    }))]

    if (categoriesState[0].category !== storage.UNCATEGORIZED) {
      const index = categoriesState.findIndex(c => c.category === storage.UNCATEGORIZED)
      const delCatState = categoriesState.splice(index, 1)
      categoriesState.unshift(delCatState[0])
    }

    this.setData({
      categories, categoriesState
    })

  },

  calculateCatNoteCounts() {
    const noteCounts = {}
    let allNoteCounts = 0
    this.data.categories.forEach(cat => {
      noteCounts[cat] = storage.getNotesByCategory(cat).length
      allNoteCounts += noteCounts[cat]
    })
    this.setData({ noteCounts, allNoteCounts })
  },

  loadNotes(category) {
    let notes = []
    if (category === '') {
      // 显示全部笔记
      const allCategories = storage.getCategories()
      allCategories.forEach(cat => {
        const catNotes = storage.getNotesByCategory(cat)
        const newCatNotes = catNotes.slice().map(note => {
          return {
            ...note,
            category: cat,  // 添加分类信息
            createdAtText: date.formatDate(note.createdAt),
            updatedAtText: note.updatedAt ? date.formatDate(note.updatedAt, 'yyyy/MM/dd') : '',
            shortContent: note.content.text.substring(0, 50),
            hasImage: note.content.html.indexOf('<img') !== -1,
            checked: false
          }
        })
        notes = notes.concat(newCatNotes)
      })
      // 按创建时间排序
      notes.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
    } else {
      // 显示特定分类笔记
      notes = storage.getNotesByCategory(category).slice().map(note => {
        return {
          ...note,
          createdAtText: date.formatDate(note.createdAt),
          updatedAtText: note.updatedAt ? date.formatDate(note.updatedAt, 'yyyy/MM/dd') : '',
          shortContent: note.content.text.substring(0, 50),
          hasImage: note.content.html.indexOf('<img') !== -1,
          checked: false
        }
      })
    }

    if (notes.length === 0) {
      this.setData({ notes: [] })
      return
    }
    this.setData({
      notes: [...notes] || [], scrollTop: 0
    })
  },

  switchCategory(e) {
    const category = e.currentTarget.dataset.category
    this.setData({
      config: { ...this.data.config, activeCategory: category },
      showSidebar: false
    }, () => {
      storage.setConfig(this.data.config)
      this.loadData()
    })
  },

  toggleNewCategory() {
    this.setData({
      ['newCategoryState.visible']: !this.data.newCategoryState.visible
    })
  },

  onCategoryInput(e) {
    this.setData({
      newCategoryState: { category: e.detail.value, visible: true }
    })
  },

  addCategory() {
    const { category } = this.data.newCategoryState
    if (!category.trim()) {
      this.setData({ newCategoryState: { visible: false, category: '' } })
      return
    }

    if (storage.addCategory(category)) {
      this.setData({ newCategoryState: { visible: false, category: '' } })
      this.loadCategories()
      this.calculateCatNoteCounts()
      wx.showToast({
        title: '添加成功',
        icon: 'success'
      })
    } else {
      wx.showToast({
        title: '分类已存在',
        icon: 'none'
      })
    }
  },

  handleDeleteCategory(e) {
    const { category } = e.currentTarget.dataset

    wx.showModal({
      title: '提示',               // 弹窗标题（可选）
      content: `确定要删除此分类(${category})吗？`, // 弹窗内容（必填）
      cancelText: '取消',          // 取消按钮文字（默认“取消”）
      confirmText: '确定',         // 确定按钮文字（默认“确定”）
      // 点击确定或取消后的回调
      success: (res) => {
        if (res.confirm) {
          this.deleteCategoryOnly(category);
          this.loadData()
        } else if (res.cancel) {

        }
      }
    });
  },

  deleteCategoryOnly(category) {
    storage.deleteCategory(category)
  },

  toggleSidebar() {
    this.setData({
      showSidebar: !this.data.showSidebar
    })
  },

  // 创建新笔记，不需要选择分类
  createNewNote() {
    this.setData({
      showSidebar: false
    }, () => {
      wx.navigateTo({
        url: `/pages/note/note?category=${this.data.config.activeCategory}`
      })
    })
  },

  editNote(e) {
    const { id, category, checked } = e.currentTarget.dataset

    if (this.data.onAction) {
      const index = this.data.notes.findIndex(n => n.id === id)

      this.cacheCheckedNotes(checked, index)
      this.setData({ [`notes[${index}].checked`]: !checked })
      return
    }

    this.setData({
      showSidebar: false
    }, () => {
      wx.navigateTo({
        url: `/pages/note/note?id=${id}${category ? `&category=${category}` : ''}`,
        success: function (res) {
          // 通过eventChannel发出切换动画类型的消息
          res.eventChannel.emit('changeAnimation', {
            animationType: 'fade'
          });
        }
      })
    })
  },

  cacheCheckedNotes(checked, index) {
    if (!checked) {
      if (this.data.actionState.checkedNotes.findIndex(i => i === index) === -1) {
        this.data.actionState.checkedNotes.push(index)
      }
    }
    else {
      const delIndex = this.data.actionState.checkedNotes.findIndex(i => i === index)
      if (delIndex !== -1) {
        this.data.actionState.checkedNotes.splice(delIndex, 1)
      }
    }

    this.setData({ ['actionState.selectedAll']: this.data.actionState.checkedNotes.length === this.data.notes.length })
  },

  // 长按列表项触发
  onNoteItemLongPress(e) {
    if (!this.data.onAction) {
      this.setData({
        onAction: !this.data.onAction
      });
    }

    this.editNote(e)
  },

  // 隐藏菜单
  cancelOnAction() {
    this.setData({ onAction: false })
    this.setData({ ['actionState.selectedAll']: false })
    this.data.actionState.checkedNotes.forEach(index => {
      this.setData({ [`notes[${index}].checked`]: false });
    })
    this.data.actionState.checkedNotes = []
  },

  handleDelete() {
    wx.showModal({
      title: '删除确认',
      content: '确定要删除选择的笔记吗？',
      complete: (res) => {
        if (res.confirm) {
          this.deleteNotes(this.data.actionState.checkedNotes.map(index => this.data.notes[index]))
        }
      }
    })
  },

  // 删除操作
  deleteNotes(notes) {
    notes.forEach(note => {
      storage.deleteNote(note.category, note.id)
    })
    this.data.actionState.checkedNotes = []
    this.setData({ onAction: false })
    this.setData({ ['actionState.selectedAll']: false })
    this.loadData()

    wx.showToast({
      title: "删除成功",
      icon: "success"
    });
  },

  selectAllNotes() {
    this.setData({
      notes: this.data.notes.map(note => ({ ...note, checked: !this.data.actionState.selectedAll }))
    })
    if (!this.data.actionState.selectedAll) {
      this.setData({ ['actionState.selectedAll']: true })
      for (let index = 0; index < this.data.notes.length; index++) {
        this.data.actionState.checkedNotes.push(index)
      }
    }
    else {
      this.setData({ ['actionState.selectedAll']: false })
      this.data.actionState.checkedNotes = []
    }
  },

  onPickerCategoryChange(e) {
    const index = e.detail.value
    const category = this.data.categoriesState[index].category
    this.setData({ ['actionState.selectedCategory']: category })

    this.data.actionState.checkedNotes.forEach(nodeIndex => {
      const note = this.data.notes[nodeIndex]
      this.moveToCategory(note, category)
    })

    this.data.actionState.checkedNotes = []

    this.cancelOnAction();

    wx.showToast({
      title: "移动成功",
      icon: "success"
    });

    this.loadData()
  },

  moveToCategory(note, toCategory) {
    const fromCategory = note.category
    note.category = toCategory
    storage.moveNoteToCategory(note.id, fromCategory, toCategory)
  }
})